package com.spzx.product.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.core.constant.MqConstants;
import com.spzx.product.service.ISkuStockService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;

import static org.springframework.amqp.rabbit.annotation.Exchange.TRUE;


/**
 * Package: com.spzx.product.receiver
 *
 * @author xiongkunYang
 * @description:
 * @since 2025/6/8 19:07
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ProductReceiver {

    private final ISkuStockService skuStockService;


    /**
     * 解锁库存
     *
     * @param orderNo 订单编号
     * @param message 消息
     * @param channel 通道
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConstants.EXCHANGE_PRODUCT),
            value = @Queue(value = MqConstants.QUEUE_UNLOCK, durable = TRUE),
            key = {MqConstants.ROUTING_UNLOCK}
    ))
    public void unlock(String orderNo, Message message, Channel channel) {
        Assert.notNull(orderNo, "订单编号不能为空");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("订单编号：{}，解锁库存成功", orderNo);
            skuStockService.unlockStock(orderNo);

            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            log.error("解锁库存失败，订单编号：{}", orderNo, e);
            channel.basicNack(deliveryTag, false, false);
        }
    }


    /**
     * 扣减库存
     *
     * @param orderNo 订单编号
     * @param message 消息
     * @param channel 通道
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConstants.EXCHANGE_PRODUCT),
            value = @Queue(value = MqConstants.QUEUE_MINUS, durable = "true"),
            key = {MqConstants.ROUTING_MINUS}
    ))
    public void minus(String orderNo, Message message, Channel channel) {
        Assert.notNull(orderNo, "订单编号不能为空");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("订单编号：{}，扣减库存成功", orderNo);
            skuStockService.minusStock(orderNo);

            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            log.error("订单编号：{}， 扣减库存失败", orderNo, e);
            channel.basicNack(deliveryTag, false, false);
        }

    }
}